package jackson;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

import java.io.IOException;

/**
 * .
 *
 * @author sunhao(sunhao.java@gmail.com)
 * @version V1.0, 16/1/14 下午7:07
 */
public class TestJackson {
    public static void main(String[] args) throws IOException {
        Demo demo = new Demo();
        demo.setName("sunhao");
        demo.setSex(Sex.MEN);

        ObjectMapper objectMapper = new CustomObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        //转成json
        String paramsJson = objectMapper.writeValueAsString(demo);
        System.out.println(paramsJson);

        Demo demo_ = objectMapper.readValue(paramsJson, Demo.class);
        System.out.println(demo_);
    }

    static class Demo {
        private String name;
        @JsonDeserialize(using = EnumDeserializer.class)
        private Sex sex;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Sex getSex() {
            return sex;
        }

        public void setSex(Sex sex) {
            this.sex = sex;
        }

        @Override
        public String toString() {
            return "Demo{" +
                    "name='" + name + '\'' +
                    ", sex=" + sex +
                    '}';
        }
    }

    enum Sex implements Codeable {
        MEN("100", "男"), WOMEN("101", "女");

        private String code;
        private String title;

        Sex(String code, String title) {
            this.code = code;
            this.title = title;
        }

        @Override
        public String getCode() {
            return code;
        }

        @Override
        public String getTitle() {
            return title;
        }
    }
}
